package com.longxi.tianjintianbao.ui.presenter.oa;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.widget.EditText;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.model.OAAuditing;
import com.longxi.tianjintianbao.model.OAPersonnel;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.oa.ICostApplyAtView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NumberToCN;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class CostApplyAtPresenter extends BasePresenter<ICostApplyAtView> {

    private String typeName = "";
    private String type = "";

    private String mAuditingId = "";
    private String mPersonnelId = "";

    public CostApplyAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
        typeName =intent.getStringExtra(AppConst.TYPENAME);
        type =intent.getStringExtra(AppConst.TYPE);
        mContext.setTitle(typeName);
        mContext.setTvLeft(MyUtils.getString(R.string.back));
    }

    public void saveCostApply() {
        String billid = "";
        long userid = MyApplication.loginUser.userid;
        String projectname = getEditText(getView().getEtProjectName());
        String use = getEditText(getView().getEtUse());
        String loantype = getView().getTvLoanType().getText().toString().trim();
        String upperamount = getEditText(getView().getEtUpperAmount());
        String loweramount = getEditText(getView().getEtLowerAmount());
        String supplier = getEditText(getView().getEtSupplier());
        String accounts = getEditText(getView().getEtAccounts());
        String openingbank = getEditText(getView().getEtOpeningBank());
        String explain = getEditText(getView().getEtExplain());

        if("".equals(loantype) || loantype == null){
            MyUtils.showToast("请选择借款方式");
            return;
        }

        if("".equals(loweramount) || loweramount == null){
            MyUtils.showToast("请输入申请金额小写");
            return;
        }

        if("".equals(upperamount) || upperamount == null){
            MyUtils.showToast("请输入申请金额大写");
            return;
        }

        if("".equals(mAuditingId) || mAuditingId == null){
            MyUtils.showToast("请选择审批流程");
            return;
        }

        if("".equals(mPersonnelId) || mPersonnelId == null){
            MyUtils.showToast("请选择下级审批人");
            return;
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", billid);
            object.put("userid", userid);
            object.put("projectname", projectname);
            object.put("use", use);
            object.put("loantype", loantype);
            object.put("upperamount", upperamount);
            object.put("loweramount", loweramount);
            object.put("supplier", supplier);
            object.put("accounts", accounts);
            object.put("openingbank", openingbank);
            object.put("explain", explain);
            object.put("auditingid", mAuditingId);
            object.put("personnelid", mPersonnelId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().saveCostApply(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                MyUtils.showToast("提交成功");
                mContext.setResult(mContext.RESULT_OK);
                mContext.finish();
            }
        });
    }

    public String getEditText(EditText editText){
        return editText.getText().toString().trim();
    }

    /**
     * 将填写的金额转大写
     */
    public void SwitchNumToUpper() {
        String lowerAmount = getView().getEtLowerAmount().getText().toString().trim();
        BigDecimal bd = null;
        if(!TextUtils.isEmpty(lowerAmount)){
            bd=new BigDecimal(lowerAmount);
        }else{
            MyUtils.showToast("请输入正确的小写金额");
            getView().getEtUpperAmount().setText("");
            return;
        }

        String chinaRMB = NumberToCN.number2CNMontrayUnit(bd);
        getView().getEtUpperAmount().setText(chinaRMB);
    }

    /**
     * 选择借款方式
     */
    public void showLoanTypeDialog() {
        AlertDialog.Builder builder =new AlertDialog.Builder(mContext);
        builder.setTitle("请选择借款方式");
        final String [] items = {"现金","支票","汇款","网银"};
        builder.setItems(items, new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                MyUtils.showToast(items[which]);
                getView().getTvLoanType().setText(items[which]);
            }
        });
        builder.show();
    }

    /**
     * 选择审批流程
     */
    public void showAuditing(){
        mContext.showWaitingDialog(MyUtils.getString(R.string.load));

        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.getUserid());
            object.put("type", type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().getOAAuditing(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<OAAuditing>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<OAAuditing> oaAuditingResponse) {
                mContext.hideWaitingDialog();
                if(oaAuditingResponse.getCode() != 0){
                    MyUtils.showToast(oaAuditingResponse.getMsg());
                    return;
                }
                List<String> arrayList = new ArrayList<>();
                for (OAAuditing oaAuditing : oaAuditingResponse.getData()) {
                    arrayList.add(oaAuditing.getAuditingname());
                }

                String[] items = arrayList.toArray(new String[]{});
                AlertDialog.Builder builder =new AlertDialog.Builder(mContext);
                builder.setTitle("请选择审批流程");
                builder.setItems(items, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        mAuditingId = oaAuditingResponse.getData().get(which).getAuditingid();
                        getView().getTvAuditingName().setText(items[which]);
                        mPersonnelId = "";
                        getView().getTvPersonnelName().setText("");
                        MyUtils.showToast(items[which]);
                    }
                });
                builder.show();
            }
        });
    }

    /**
     * 选择下级审批人
     */
    public void showPersonnel(){
        if(TextUtils.isEmpty(mAuditingId)){
            MyUtils.showToast("请先选择审批流程");
            return;
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));

        JSONObject object = new JSONObject();
        try {
            object.put("billid", "");
            object.put("userid", MyApplication.loginUser.getUserid());
            object.put("auditingid", mAuditingId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().getOAPersonnel(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<OAPersonnel>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<OAPersonnel> oaPersonnelResponse) {
                mContext.hideWaitingDialog();
                if(oaPersonnelResponse.getCode() != 0){
                    MyUtils.showToast(oaPersonnelResponse.getMsg());
                    return;
                }
                List<String> arrayList = new ArrayList<>();
                for (OAPersonnel oaPersonnel : oaPersonnelResponse.getData()) {
                    arrayList.add(oaPersonnel.getPersonnelname());
                }

                String[] items = arrayList.toArray(new String[]{});
                AlertDialog.Builder builder =new AlertDialog.Builder(mContext);
                builder.setTitle("请选择下级审批人");
                builder.setItems(items, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        mPersonnelId = oaPersonnelResponse.getData().get(which).getPersonnelid();
                        getView().getTvPersonnelName().setText(items[which]);
                        MyUtils.showToast(items[which]);
                    }
                });
                builder.show();
            }
        });
    }
}
